<template>
  <div>
    <my-breadcrumb :items="['订单管理', '订单详情']"></my-breadcrumb>
    <Card :dis-hover="true" :padding="10">
      <span class="back" @click="goBack"><Icon type="arrow-left-c"></Icon>上一页</span>
    </Card>
    <div class="step">
      <Steps :current="1">
        <Step title="下单" content="2018-08-11 15:15:00"></Step>
        <Step title="已付款" content="2018-08-11 15:15:00"></Step>
        <Step title="已发货" content="2018-08-11 15:15:00"></Step>
        <Step title="交易完成" content="2018-08-11 15:15:00"></Step>
      </Steps>
    </div>
    <Button type="primary" @click="printOrder">打印发货单</Button>
    <div class="order">
      <Row :gutter="16">
        <i-col span="8">
          <div class="card">
            <div class="title">订单信息</div>
            <div class="content">
              <ul>
                <li>
                  <div style="float: left;">
                    <span>订单编号：</span>
                  </div>
                  <div style="float: left;width: 200px;">
                    <span>{{orderInfo.orderNumber}}</span>
                  </div>
                </li>
                <li>
                  <span>付款人：<img :src="userData.profilePhotoPath" alt="头像" width="40">{{ userData.nickname }}</span>
                </li>
                <li>
                  <span>订单总价：{{ orderInfo.orderDiscountTotal / 100 }}￥</span>
                </li>
                <li>
                  <span>商品总数：{{ orderInfo.itemQuantityTotal }}</span>
                </li>
              </ul>
            </div>
          </div>
        </i-col>
        <i-col span="8">
          <div class="card">
            <div class="title">地址</div>
            <div class="content">
              <ul class="address">
                <li>
                  <span>收货地址：</span>
                  <p>{{ orderInfo.consigneeAddress }} {{orderInfo.consigneeName}} {{orderInfo.consigneePhone}}</p>
                </li>
                <li>
                  <span>发货地址：</span>
                  <p v-if="deliveryAddress.address">{{ deliveryAddress.address }} {{ deliveryAddress.name }} {{ deliveryAddress.phone }}</p>
                  <p v-else>{{ addressList[0].province }} {{ addressList[0].city }} {{ addressList[0].county }} {{ addressList[0].address }} {{ addressList[0].name }} {{ addressList[0].phone }}</p>
                </li>
              </ul>
            </div>
          </div>
        </i-col>
        <i-col span="8">
          <div class="card">
            <div class="title">买家留言</div>
            <div class="content buyer">
              {{ orderInfo.remark }}
            </div>
          </div>
        </i-col>
      </Row>
    </div>
    <div class="finish" v-show="finishData[0]">
      <div class="title">已经发货部分</div>
      <div v-for="(data, index) in finishData" :key="index" class="finish_item">
        <div class="shipping_top">
          <span>快递：{{ data.logisticsName }} </span>
          <span>单号：{{ data.logisticsNumber }}</span>
          <span>发货人：{{ data.shipperName }}</span>
          <span>发货人电话：{{ data.shipperPhone }}</span>
          <span>发货地址：{{ data.shipperAddress }}</span>
          <div style="float: right;">
            <Button type="text" @click="showCutTab(data.id, index)">发货图片、快递单</Button>
          </div>
        </div>
        <Table :columns="finishShipping" :data="data.items"></Table>
      </div>
    </div>
    <div class="pack">
      <div class="title">打包二维码单</div>
      <div>
        <Table :columns="finishPack" :data="packData" ref="packTable"></Table>
        <Table :columns="printPack" :data="packData" ref="printTable" class="table"></Table>
        <div v-show="packData[0]">
          <div class="title" style="margin-top: 16px;">填写发货信息</div>
          <div class="form">
            <Form :label-width="70" inline :model="send">
              <FormItem label="物流公司" v-if="inputLog && isSelf">
                <Input v-model="send.logisticsName" style="width: 150px;"/>
              </FormItem>
              <FormItem label="物流公司" v-if="!inputLog && isSelf">
                <Select v-model="send.logisticsId" style="width: 150px;">
                  <Option v-for="(com, index) in companys" :key="index" :value="com.id">{{com.courierCompanyName}}</Option>
                </Select>
              </FormItem>
              <Button type="primary" @click="inputLog = !inputLog" v-if="canInput">{{ inputLog ? '输入' : '选择' }}</Button>
              <FormItem label="物流单号" v-if="isSelf">
                <Input v-model="send.logisticsNumber"/>
              </FormItem>
              <FormItem label="包裹数量">
                <InputNumber :min="1" v-model="send.packageQuantity"/>
              </FormItem>
              <FormItem label="发货地址" style="width: 350px" v-if="!haveAddress">
                <Select v-model="send.shippingAddressId">
                  <Option v-for="(item, index) in addressList" :key="index" :value="item.id">{{item.province}} {{item.city}} {{item.county}} {{item.address}}</Option>
                </Select>
              </FormItem>
            </Form>
          </div>
          <Button type="primary" long @click="createShipping">发货</Button>
        </div>
      </div>
    </div>
    <Modal v-model="showImg" title="图片展示(点击可更新)" :styles="{top: '20px'}" :width="600">
      <div class="all">
        <div class="fl_img">
          <Upload
            ref="upload"
            :format="['jpg','jpeg','png']"
            :max-size="2048"
            :before-upload="handleBeforeUpload"
            type="drag"
            action="#"
            style="display: inline-block;width:100px;">
            <div style="width: 100px;height:100px;line-height: 100px;position: relative;" @click="setLogUpload">
              <p><Icon type="camera" size="20"></Icon><span>上传快递单</span></p>
              <div style="position: absolute;top: 0;left: 0;">
                <img :src="logImgPath" alt="" width="100" v-if="logImgPath">
              </div>
            </div>
          </Upload>
        </div>
        <div class="fr_img">
          <Upload
            v-for="(img, index) in shippingImgs"
            :key="index"
            ref="upload"
            :format="['jpg','jpeg','png']"
            :max-size="2048"
            :before-upload="handleBeforeUpload"
            type="drag"
            action="#"
            style="display: inline-block;width:100px;">
            <div style="width: 100px;height:100px;line-height: 100px;" @click="setShippingUpload(index)">
              <img :src="'https://hycos-1257620396.file.myqcloud.com' + img.imagePath" alt="tupian" width="100">
            </div>
          </Upload>
          <Upload
            v-if="shippingImgs.length < 5"
            ref="upload"
            :format="['jpg','jpeg','png']"
            :max-size="2048"
            :before-upload="handleBeforeUpload"
            type="drag"
            action="#"
            style="display: inline-block;width:170px;">
            <div style="width: 170px;height:100px;line-height: 100px;" @click="setShippingUpload">
              <p><Icon type="camera" size="20"></Icon><span>上传发货图片（最多五张）</span></p>
            </div>
          </Upload>
        </div>
      </div>
    </Modal>
    <imageUtil ref="imageUtil" @cropImg="cropImg"></imageUtil>
    <Modal v-model="showRemark" @on-ok="addCheckImg">
      图片备注：<Input v-model="remark" placeholder="备注" width="400"/>
    </Modal>
  </div>
</template>

<script>
import imageUtil from '../../common/imageUtil'
import QRCode from 'qrcode'
export default {
  name: 'order-detail',
  data () {
    return {
      url: {
        info: '/shipping/info',
        create: '/shipping/create',
        list: '/branch/common/logistics/list',
        packUpdate: '/shipping/pack/quantity/update',
        address: '/shipping/address/list',
        checkAdd: '/shipping/check/add',
        checkUpdate: '/shipping/check/update',
        logImg: '/shipping/logistics/image/update'
      },
      userData: {},
      shippingNum: [],
      // 图片数据
      blobArr: null,
      // 图片展示
      showImg: false,
      imgIndex: -1,
      // 已完成发货数据
      finishShipping: [
        {
          title: '商品',
          key: 'goods',
          render: (h, params) => {
            return h('div', {
              style: {
                overflow: 'hidden',
                padding: '6px'
              }
            }, [
              h('img', {
                attrs: {
                  width: '50px',
                  height: '50px',
                  src: this.staticUrl + params.row.goodsImagePath
                },
                style: {
                  float: 'left'
                }
              }),
              h('div', {
                style: {
                  float: 'left',
                  marginLeft: '6px'
                }
              }, [
                h('p', params.row.goodsTitle)
              ])
            ])
          }
        },
        {
          title: '单价',
          key: 'goodsDiscountPrice',
          width: 100,
          render: (h, params) => {
            return h('div', [
              h('p', {
                style: {
                  fontWeight: '800'
                }
              }, params.row.goodsDiscountPrice / 100 + '￥')
            ])
          }
        },
        {
          title: '数量',
          key: 'purchaseQuantity',
          width: 100
        },
        {
          title: '总价',
          key: 'goodsDiscountTotal',
          width: 100,
          render: (h, params) => {
            // goodsDiscountTotal
            return h('div', [
              h('p', {
                style: {
                  fontWeight: '800'
                }
              }, params.row.goodsDiscountTotal / 100 + '￥')
            ])
          }
        },
        {
          title: '本次打包',
          key: 'packQuantity',
          width: 100
        },
        {
          title: '本次发货',
          key: 'shippingQuantity',
          width: 100
        }
      ],
      finishData: [],
      // 未发货表格数据
      unshipping: [],
      // 所有物流公司
      companys: [],
      // 现在的打包值
      nowVal: null,
      // 已打包表格头
      finishPack: [
        {
          title: '商品',
          key: 'goods',
          render: (h, params) => {
            const imgUrl = 'https://hycos-1257620396.file.myqcloud.com'
            return h('div', {
              style: {
                overflow: 'hidden',
                padding: '6px'
              }
            }, [
              h('img', {
                attrs: {
                  width: '50px',
                  height: '50px',
                  src: imgUrl + params.row.goodsImagePath
                },
                style: {
                  float: 'left'
                }
              }),
              h('div', {
                style: {
                  float: 'left',
                  marginLeft: '6px'
                }
              }, [
                h('p', params.row.goodsTitle)
              ])
            ])
          }
        },
        {
          title: '单价',
          key: 'goodsDiscountPrice',
          width: 100,
          render: (h, params) => {
            return h('div', [
              h('p', {
                style: {
                  fontWeight: '800'
                }
              }, params.row.goodsDiscountPrice / 100 + '￥')
            ])
          }
        },
        {
          title: '总数',
          key: 'purchaseQuantity',
          width: 70
        },
        {
          title: '已发货数量',
          key: 'goodsSentQuantity',
          width: 100
        },
        {
          title: '剩余发货数',
          width: 100,
          align: 'center',
          render: (h, params) => {
            return h('span', {
              style: {
                color: '#ed3f14',
                fontWeight: '600'
              }
            }, params.row.purchaseQuantity - params.row.goodsSentQuantity)
          }
        },
        {
          title: '总价',
          key: 'unprocessedAmountTotal',
          width: 100,
          render: (h, params) => {
            return h('div', [
              h('p', {
                style: {
                  fontWeight: '800'
                }
              }, params.row.unprocessedAmountTotal / 100 + '￥')
            ])
          }
        },
        {
          title: '本次发货数',
          key: '',
          width: 100,
          render: (h, params) => {
            let _self = this
            return h('InputNumber', {
              props: {
                value: _self.shippingNum[params.index] ? _self.shippingNum[params.index] : 0,
                min: 0
              },
              on: {
                input: (e) => {
                  _self.shippingNum[params.index] = e
                }
              }
            })
          }
        },
        {
          title: '当前打包数量',
          key: 'packQuantity',
          width: 120,
          render: (h, params) => {
            return h('InputNumber', {
              props: {
                value: params.row.currentPackedQuantity,
                min: 0,
                max: params.row.purchaseQuantity - params.row.goodsSentQuantity
              },
              on: {
                input: (e) => {
                  params.row.currentPackedQuantity = e
                },
                'on-change': () => {
                  this.setPackNum(params.row)
                },
                'on-focus': () => {
                  this.nowVal = params.row.currentPackedQuantity
                }
              }
            })
          }
        },
        {
          title: '打包码',
          key: 'packQrcodeImagePath',
          render: (h, params) => {
            return h('img', {
              attrs: {
                width: '80px',
                id: params.index + 'I'
              }
            })
          }
        }
      ],
      printPack: [
        {
          title: '商品',
          key: 'goods',
          width: 160,
          render: (h, params) => {
            const imgUrl = 'https://hycos-1257620396.file.myqcloud.com'
            return h('div', {
              style: {
                overflow: 'hidden',
                padding: '6px'
              }
            }, [
              h('img', {
                attrs: {
                  width: '50px',
                  height: '50px',
                  src: imgUrl + params.row.goodsImagePath
                },
                style: {
                  float: 'left'
                }
              }),
              h('div', {
                style: {
                  float: 'left',
                  marginLeft: '6px'
                }
              }, [
                h('p', params.row.goodsTitle)
              ])
            ])
          }
        },
        {
          title: '单价',
          key: 'goodsDiscountPrice',
          width: 90,
          render: (h, params) => {
            return h('div', [
              h('p', {
                style: {
                  fontWeight: '800'
                }
              }, params.row.goodsDiscountPrice / 100 + '￥')
            ])
          }
        },
        {
          title: '总数',
          key: 'purchaseQuantity',
          width: 80
        },
        {
          title: '已发货数量',
          key: 'goodsSentQuantity',
          width: 80
        },
        {
          title: '剩余发货数',
          align: 'center',
          width: 80,
          render: (h, params) => {
            return h('span', {
              style: {
                color: '#ed3f14',
                fontWeight: '600'
              }
            }, params.row.purchaseQuantity - params.row.goodsSentQuantity)
          }
        },
        {
          title: '总价',
          key: 'unprocessedAmountTotal',
          width: 80,
          render: (h, params) => {
            return h('div', [
              h('p', {
                style: {
                  fontWeight: '800'
                }
              }, params.row.unprocessedAmountTotal / 100 + '￥')
            ])
          }
        },
        {
          title: '打包码',
          key: 'packQrcodeImagePath',
          width: 110,
          render: (h, params) => {
            return h('img', {
              attrs: {
                width: '80px',
                id: params.index + 'PI'
              }
            })
          }
        }
      ],
      packData: [],
      // 订单信息
      orderInfo: {},
      // 发货表单
      send: {
        logisticsId: null,
        logisticsName: '',
        logisticsNumber: '',
        packageQuantity: null,
        shippingAddressId: null
      },
      // 选择地址
      addressList: [{id: 0}],
      detailId: 0,
      logUpload: false,
      shippingUpload: false,
      showRemark: false,
      remark: '',
      shippingImgs: [],
      checkImgs: [],
      updateImgIndex: null,
      activeIndex: null,
      logImgPath: null,
      deliveryAddress: {},
      isSelf: false,
      inputLog: false,
      canInput: false,
      haveAddress: false,

      options: {
        errorCorrectionLevel: 'H',
        type: 'image/jpeg',
        rendererOpts: {
          quality: 0.3
        },
        margin: 0,
        width: 90
      }
    }
  },
  methods: {
    // 上传图片点击
    handleBeforeUpload (e) {
      let params = {
        e,
        name: 'shipping'
      }
      this.$refs.imageUtil.setImage(params)
      return false
    },
    // 调用子组件切图方法
    cropImg (data) {
      // this.dataArr.push(data.imgTime)
      if (this.logUpload) {
        // 快递单
        let formData = new FormData()
        formData.append('detailId', this.detailId)
        formData.append('file', data.blob, 'file.jpg')
        this.$ajax.post(this.url.logImg, formData, {header: {'Content-Type': 'multipart/form-data'}})
          .then(res => {
            if (res.data.success) {
              this.logImgPath = data.imgTime
              this.finishData[this.activeIndex].logisticsImagePath = data.imgTime
            }
          })
      } else if (this.shippingUpload) {
        // 写备注
        this.showRemark = true
        this.blobArr = data.blob
      }
    },
    // 查看图片
    lookImg (i) {
      this.showImg = true
      this.imgIndex = i
    },
    // 删除图片
    deleteImg (i) {
      let _self = this
      this.$Modal.confirm({
        title: '图片删除',
        content: '确认要删除这张图片吗？',
        onOk: () => {
          this.dataArr.splice(i, 1)
          this.blobArr.splice(i, 1)
          _self.$Message.success('已删除')
        }
      })
    },
    // 发货按钮
    createShipping () {
      let params = {...this.send, orderId: this.$route.query.id}
      if (!this.isSelf) {
        delete params.logisticsId
        delete params.logisticsName
        delete params.logisticsNumber
      }
      if (this.inputLog) {
        delete params.logisticsId
      } else {
        delete params.logisticsName
      }
      if (this.haveAddress) {
        delete params.shippingAddressId
      }
      console.log(params)
      for (let i in params) {
        if (!params[i]) {
          this.$Message.error('填写正确信息再提交')
          return
        }
      }
      let quantityItem = []
      this.shippingNum.forEach((item, index) => {
        if (item) {
          quantityItem.push({
            itemId: this.packData[index].id,
            quantity: item
          })
        }
      })
      params.quantityItem = quantityItem
      params.freight = 0
      this.$ajax.post(this.url.create, JSON.stringify(params)).then(res => {
        if (res.data.success) {
          this.$Message.success('发货成功')
          this.getInfo()
        }
      })
    },
    // 设置打包值
    setPackNum (row) {
      if (row.currentPackedQuantity !== this.nowVal) {
        this.$ajax.post(this.url.packUpdate, [{quantity: row.currentPackedQuantity, itemId: row.id}]).then(res => {
          if (res.data.success) {
            this.$Message.success('修改成功')
          } else {
            row.currentPackedQuantity = this.nowVal
          }
        })
      }
    },
    // 初始化刷新数据
    getInfo () {
      this.$ajax.post(this.url.info, this.$route.query.id).then(res => {
        if (res.data.success) {
          if (res.data.data.specifyShippingAddressJson) {
            this.deliveryAddress = JSON.parse(res.data.data.specifyShippingAddressJson)
            this.haveAddress = true
          }
          this.shippingImgs = res.data.data.shippingChecks
          this.finishData = []
          // 订单全部信息
          this.orderInfo = res.data.data
          // 购买用户信息
          this.userData = res.data.data.userInfoVO
          // 总
          this.packData = res.data.data.unprocessedItem
          this.$nextTick(() => {
            this.setCode()
          })
          // 发货部分
          let temp = []
          res.data.data.shippingDetails.forEach(item => {
            item.items = []
            temp[item.id] = item
          })
          res.data.data.shippingDetailItems.forEach(item => {
            temp[item.shippingDetailId].items.push(item)
          })
          res.data.data.shippingChecks.forEach(item => {
            if (!this.checkImgs['img' + item.shippingDetailId]) {
              this.checkImgs['img' + item.shippingDetailId] = []
            }
            this.checkImgs['img' + item.shippingDetailId].push(item)
          })
          for (let i in temp) {
            this.finishData.push(temp[i])
          }
          if (res.data.data.logisticsMode === 1 || res.data.data.logisticsMode === 2) {
            this.getCompanyList(res.data.data.logisticsMode)
            this.isSelf = true
          }
          if (res.data.data.logisticsMode === 2) {
            this.canInput = true
          }
        }
      })
    },

    // 设置打包码
    setCode () {
      this.packData.forEach((item, index) => {
        QRCode.toDataURL('/pack/plugin?v=' + item.id, this.options, (err, url) => {
          if (!err) {
            document.getElementById(index + 'I').src = url
            document.getElementById(index + 'PI').src = url
          }
        })
      })
    },

    // 打印
    printOrder () {
      document.body.innerHTML = document.getElementsByClassName('order')[0].innerHTML + this.$refs.printTable.$el.innerHTML
      window.print()
      window.location.reload()
    },
    // 返回上一页
    goBack () {
      this.$router.go(-1)
    },
    getAddress () {
      this.$ajax.post(this.url.address).then(res => {
        if (res.data.success) {
          this.addressList = res.data.data
        }
      })
    },
    getCompanyList (type) {
      this.$ajax.post(this.url.list, type).then(res => {
        if (res.data.success) {
          this.companys = res.data.data
        }
      })
    },
    // 图片
    showCutTab (id, index) {
      if (this.finishData[index].logisticsImagePath) {
        if (this.finishData[index].logisticsImagePath.length < 100) {
          this.logImgPath = 'https://hycos-1257620396.file.myqcloud.com' + this.finishData[index].logisticsImagePath
        }
      } else {
        this.logImgPath = null
      }
      if (!this.checkImgs['img' + id]) {
        this.checkImgs['img' + id] = []
      }
      this.shippingImgs = this.checkImgs['img' + id]
      this.showImg = true
      this.detailId = id
      this.activeIndex = index
    },
    setLogUpload () {
      this.logUpload = true
      this.shippingUpload = false
    },
    setShippingUpload (index) {
      if (typeof index === 'number') {
        this.updateImgIndex = index
      }
      this.logUpload = false
      this.shippingUpload = true
    },
    addCheckImg () {
      let formData = new FormData()
      if (this.updateImgIndex !== null) {
        // 更新
        this.updateCheck(formData)
      } else {
        this.addCheck(formData)
      }
    },
    addCheck (formData) {
      formData.append('file', this.blobArr, 'file.jpg')
      formData.append('detailId', this.detailId)
      formData.append('remark', this.remark)
      this.$ajax.post(this.url.checkAdd, formData, {header: {'Content-Type': 'multipart/form-data'}})
        .then(res => {
          if (res.data.success) {
            this.shippingImgs.push(res.data.data)
          }
        })
    },
    updateCheck (formData) {
      let updateJson = {
        checkId: this.shippingImgs[this.updateImgIndex].id,
        remark: this.remark
      }
      formData.append('shippingCheckUpdateJson', JSON.stringify(updateJson))
      formData.append('file', this.blobArr, 'file.jpg')
      this.$ajax.post(this.url.checkUpdate, formData, {header: {'Content-Type': 'multipart/form-data'}})
        .then(res => {
          if (res.data.success) {
            this.shippingImgs.splice(this.updateImgIndex, 1, res.data.data)
            this.updateImgIndex = null
          }
        })
    }
  },
  components: {
    imageUtil
  },
  created () {
    this.getInfo()
    this.getAddress()
  }
}
</script>

<style scoped>
.back{
  cursor: pointer;
}
  .step{
    margin-top: 30px;
    margin-left: 20px;
    margin-bottom: 30px;
  }
  .card{
    border: 1px solid #dddee1;
    height: 200px;
    box-sizing: border-box;
  }
  .title{
    height: 30px;
    line-height: 30px;
    padding-left: 12px;
    font-size: 12px;
    font-weight: 800;
    background-color: #eee;
    border-bottom: 1px solid #dddee1;
  }
  .content{
    padding: 10px;
    overflow: hidden;
    font-size: 12px;
  }
  .content.buyer{
    height: 200px;
  }
  .content li{
    overflow: hidden;
    margin-bottom: 10px;
  }
  .address p{
    padding-left: 16px;
  }
  .success{
    font-size: 16px;
    color: #1c2438;
    display: inline-block;
    line-height: 40px;
    height: 40px;
    font-weight: 800;
    vertical-align: top;
    margin-left: 8px;
  }
  .form{
    padding-top: 16px;
    border-left: 1px solid #dddee1;
    border-right: 1px solid #dddee1;
    border-bottom: 1px solid #dddee1;
  }
  .finish{
    margin-top: 16px;
  }
  .finish_item{
    margin-bottom: 16px;
  }
  .pack{
    margin-top: 24px;
  }
  .shipping_top{
    line-height: 35px;
    height: 35px;
    border-left: 1px solid #dddee1;
    border-right: 1px solid #dddee1;
    border-top: 1px solid #dddee1;
    padding-left: 10px;
  }
  .shipping_top span{
    margin-right: 8px;
  }
  .all{
    overflow: hidden;
  }
  .fl_img{
    float: left;
    width: 100px;
  }
  .fr_img{
    float: right;
    width: 400px;
  }
  .table{
    display: none;
    float: left;
  }
</style>
